﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
using com.lover.common;
using System.IO;
using com.lover.astd.common.model;
using com.lover.astd.common.manager;
using com.lover.common.http;

namespace com.lover.astd.common.partner.impl
{
    public class XdwanLogin : LoginImplBase
    {
        public XdwanLogin() : base() { }
        public override LoginResult login(ref List<Cookie> cookies, string verify_code = null, string extra = null)
        {
            LoginResult result = new LoginResult();
            logging();
            string loginurl = String.Format(
                "http://www.xdwan.com/users/post/index.ashx?logincallback=jsonp{0}&t=login&account={1}&password={2}&cookie=0&r={3}", 
                TimeMgr.TimeStamp, _username, _password, _rand.NextDouble());
            HttpResult resp = TransferMgr.doGetPure(loginurl, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }

            string retstr = resp.getContent();

            if (retstr.IndexOf("loginvalue:'#99'") < 0)
            {
                result.StatusCode = LoginStatusCode.FailInLogin;
                return result;
            }
            // 查找serverid字符串
            string game_list_url = "http://as.xdwan.com/servers.aspx";
            resp = TransferMgr.doGetPure(game_list_url, ref cookies);
            if (resp == null) { result.StatusCode = LoginStatusCode.FailInLogin; return result; }
            string content = resp.getContent();
            string district_name = String.Format("兄弟玩{0}服", _acc.ServerId);
            //.*<a.*?href='(.*?)'>[\w\r\n\t\s]*?兄弟玩1服.*?</a>.*
            Regex re = new Regex(String.Format(".*<a.*?href=[\"']+?([^\"']*?)[\"']+?>[\\w\\r\\n\\t\\s]*?{0}.*?</a>.*", district_name));
            Match m = re.Match(content);
            if (m == null || m.Groups == null || m.Groups.Count < 2)
            {
                result.StatusCode = LoginStatusCode.FailInGotoGameUrl; return result;
            }

            string redirecturl = m.Groups[1].Value;
            //http://www.xdwan.com/GameCenter/Start/?Gameid=19&ServerID=129 ---->
            //http://www.xdwan.com/GameCenter/Start/start.ashx?Gameid=19&ServerID=129
            redirecturl = redirecturl.Replace("?Gameid", "start.ashx?Gameid");

            processRedirect(redirecturl, result, ref cookies);
            return result;
        }
    }
}
